<template>
  <view>
    <cu-custom :isBack="true">
      
    </cu-custom>

    <!-- 新增的搜索框 -->
    <view class="cu-bar bg-white search">
      <view class="search-form round">
        <text class="cuIcon-search"></text>
        <input 
          type="text" 
          placeholder="搜索卡券" 
          confirm-type="search" 
          v-model="searchKeyword"
          @confirm="performSearch"
        />
      </view>
      <view class="action">
        <button 
          class="cu-btn bg-gradual-blue shadow-blur round" 
          @click="performSearch"
        >
          搜索
        </button>
      </view>
    </view>

    <!-- 搜索结果列表 -->
    <view class="padding-lr-sm padding-tb-xs">
      <!-- 原有代码保持不变 -->
      <view v-if="loading" class="text-center padding-xl">
        <text class="cuIcon-loading2 iconfont-spin"></text>
        <text> 正在加载...</text>
      </view>
      <view v-else-if="cards.length === 0" class="text-center padding-xl text-gray">
        没有找到相关的卡券
      </view>
      
      <view v-else class="cu-card coupon" v-for="card in cards" :key="card.card_id" :class="card.is_expired ? 'expired' : ''">
        <view class="cu-item shadow-lg">
          <view class="flex">
            <view class="left">
              <view class="cu-avatar round lg bg-red">
                <text class="cuIcon-ticket"></text>
              </view>
              <view class="text-bold text-sm margin-top-xs name">{{ card.mer_name }}</view>
            </view>
            <view class="right">
              <view class="flex justify-between align-start">
                <view>
                  <view class="text-bold">{{ card.card_name }}</view>
                  <view class="text-xs text-gray margin-top-xs">满{{ card.condition }}元可用, 抵扣{{ card.card_price }}元</view>
                  <view class="text-xs text-gray margin-top-xs">有效期至: {{ card.end_time.split('T')[0] }}</view>
                </view>
								<button class="cu-btn round sm"
									:class="(card.is_expired || card.claimed) ? 'bg-grey' : 'bg-red'"
									:disabled="card.is_expired || card.claimed"
									@click="claimCard(card)">
									{{ card.claimed ? '已领取' : (card.is_expired ? '已过期' : '去领取') }}
								</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { get, post } from '@/utils/request.js';

const cards = ref([]);
const loading = ref(true);
const searchKeyword = ref('');  // 修改为searchKeyword用于绑定搜索框

onLoad(async (options) => {
  // 接收URL参数并赋值给searchKeyword
  searchKeyword.value = decodeURIComponent(options.keyword || '');
  
  if (searchKeyword.value) {
    await fetchSearchResults();
  } else {
    loading.value = false;
  }
});

// 执行搜索（可用于输入框确认事件和按钮点击）
const performSearch = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索内容',
      icon: 'none'
    });
    return;
  }
  
  // 更新URL参数但不跳转页面
  uni.redirectTo({
    url: `/pages/search/cardSearch?keyword=${encodeURIComponent(searchKeyword.value)}`
  });
};

const fetchSearchResults = async () => {
  loading.value = true;
  try {
		let userId = null;
		const storedUser = uni.getStorageSync('user');
		if (storedUser) {
			try {
				const userData = JSON.parse(storedUser);
				userId = userData.userId;
			} catch (e) {
				console.error("解析用户信息失败", e);
			}
		}

		let url = `/card/search?cardName=${searchKeyword.value}`;
		if (userId) {
			url += `&userId=${userId}`;
		}
		
    // 使用当前searchKeyword进行搜索
    const res = await get(url);
    if (res.data && res.data.msg) {
      cards.value = res.data.msg.map(card => {
				const isExpired = new Date(card.end_time) < new Date();
				return {
					...card,
					is_expired: isExpired,
					claimed: card.claimedByUser || false
				}
			});
    }
  } catch (error) {
    console.error('搜索卡券失败', error);
    uni.showToast({ title: '搜索失败，请稍后重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const claimCard = async (card) => {
    // 1. 前置检查 (登录状态等)
    const token = uni.getStorageSync('token');
    if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => uni.navigateTo({ url: '/pages/login/login' }), 1500);
        return;
    }

    if (card.claimed) {
        uni.showToast({ title: '您已领取该卡券', icon: 'none' });
        return;
    }

    // 显示加载提示
    uni.showLoading({ title: '正在领取...' });

    try {
        // 2. 准备请求参数
        const storedUser = uni.getStorageSync('user');
        const userData = JSON.parse(storedUser);
        const userId = userData.userId;

        if (!userId) {
            uni.hideLoading();
            uni.showToast({ title: '无法获取用户信息', icon: 'none' });
            return;
        }

        const payload = {
            userId: userId,
            cardId: card.card_id, // 或 card.id, 取决于您的对象
        };

        // 3. 调用后端接口
        const res = await post('/card/addCard', payload);

        uni.hideLoading();

        // 4. 处理后端响应
        // 检查 code 是否为 200，表示业务处理成功
        if (res.data && res.data.code === 200) {
            // 成功时，msg 中是完整的 Card 对象
            const claimedCardDetails = res.data.msg;
            
            // 构造成功的提示信息，并展示过期时间
            const expirationDate = claimedCardDetails.endTime ? claimedCardDetails.endTime.split('T')[0] : 'N/A';
            uni.showToast({
                title: `领取成功！有效期至 ${expirationDate}`,
                icon: 'success',
                duration: 2000 // 持续时间长一点，方便用户看清
            });
            
            // 更新UI，将按钮变为“已领取”状态
            card.claimed = true;

        } else {
            // code 不是 200，表示业务失败（如已领取、库存不足等）
            // 此时，错误信息就在 msg 字段中
            const errorMessage = (res.data && res.data.msg) || '领取失败，请稍后重试';
            uni.showToast({
                title: errorMessage,
                icon: 'none'
            });

            // 如果错误信息是“已领取”，也需要同步更新UI状态
            if (errorMessage.includes('已领取')) {
                card.claimed = true;
            }
            // 如果错误信息是“抢光了”，可以考虑将按钮禁用
            if (errorMessage.includes('抢光了')) {
                // 例如，可以新增一个状态字段 card.soldOut = true 来控制按钮的样式和可点击状态
                card.is_expired = true; // 也可以借用 is_expired 字段来达到禁用效果
            }
        }
    } catch (error) {
        // 网络层面的错误（例如服务器宕机、网络不通）
        uni.hideLoading();
        console.error('领取卡券网络异常:', error);
        uni.showToast({ title: '网络开小差了，请稍后再试', icon: 'none' });
    }
};
</script>

<style scoped>
/* 新增搜索框样式（与页面2一致） */
.search {
  padding: 10rpx 20rpx;
}
.search-form {
  flex: 1;
  background-color: #f5f5f5;
  padding: 0 20rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
}
.search-form input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  margin-left: 10rpx;
}
.action button {
  height: 70rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

/* 原有样式保持不变 */
.coupon {
	margin-top: 20rpx;
}
.coupon .cu-item {
	border-radius: 16rpx;
	overflow: hidden;
}
.coupon .left {
	width: 200rpx;
	background-color: #fff8f8;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20rpx;
	border-right: 2rpx dashed #eee;
}
.coupon .left .avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}
.coupon .left .name {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 100%;
	text-align: center;
}
.coupon .right {
	flex: 1;
	padding: 20rpx;
	background-color: #ffffff;
}
.expired {
	filter: grayscale(100%);
	opacity: 0.7;
}
.iconfont-spin {
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>